﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace Eldert.IoT.Simulator
{
    /// <summary>
    /// Class used to retrieve and save settings to the settings file.
    /// </summary>
    internal class Settings
    {
        internal const string SettingsPath = @"..\..\..\..\Settings.xml";

        private static XDocument _settingsDocument;
        private static readonly Dictionary<string, string> cache = new Dictionary<string, string>();

        private static XDocument SettingsDocument => _settingsDocument ?? (_settingsDocument = XDocument.Load(SettingsPath));

        /// <summary>
        /// Get the setting with the specified name from the settings file.
        /// </summary>
        internal static string Read(string name)
        {
            if (!cache.ContainsKey(name))
            {
                cache.Add(name, SettingsDocument.Descendants().FirstOrDefault(e => e.Name.LocalName == name).Value);
            }

            return cache[name];
        }

        internal static void Write(string name, string value)
        {
            SettingsDocument.Descendants().FirstOrDefault(e => e.Name.LocalName == name).Value = value;
            var fileStream = new FileStream(SettingsPath, FileMode.Create);
            SettingsDocument.Save(fileStream);
            fileStream.Flush();

            if (cache.ContainsKey(name))
            {
                cache[name] = value;
            }
        }
    }
}
